import { HttpException, HttpStatus, Injectable, Query } from '@nestjs/common';
import { CreatePostDto, UpdatePostDto } from './dto/post.dto';
import { Post } from './entities/post.entity';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { AdminPostPageDto, AdminPostResDto } from './dto/admin-post.dto';

@Injectable()
export class PostService {
  constructor(
    @InjectRepository(Post)
    private readonly postRepository: Repository<Post>,
  ) {}

  async create(data: CreatePostDto) {
    const findPost = await this.postRepository.findOne({
      where: { title: data.title, isDeleted: false },
    });
    if (findPost) {
      throw new HttpException('文章已存在', HttpStatus.BAD_REQUEST);
    }
    const newPost = this.postRepository.create({
      title: data.title,
      content: data.content,
      image: data.image,
    });
    return await this.postRepository.save(newPost);
  }

  async findPage(query: AdminPostPageDto): Promise<AdminPostResDto> {
    const pageNo = query.pageNo || 1;
    const pageSize = query.pageSize || 10;

    const [list, total] = await this.postRepository.findAndCount({
      where: { isDeleted: false },
      order: { createdAt: 'DESC' },
      skip: (pageNo - 1) * pageSize,
      take: pageSize,
    });

    return { list, total };
  }

  findAll() {
    return this.postRepository.find({
      where: { isDeleted: false },
      order: { createdAt: 'DESC' },
    });
  }

  async findOne(postId: number) {
    const findPost = await this.postRepository.findOne({
      where: { postId, isDeleted: false },
      select: ['content', 'postId', 'title', 'viewCount'],
    });
    if (!findPost) {
      throw new HttpException('文章不存在', HttpStatus.BAD_REQUEST);
    }
    findPost.viewCount += 1;
    await this.postRepository.save(findPost);

    return findPost;
  }

  async update(postId: number, data: UpdatePostDto) {
    const findPost = await this.postRepository.findOne({
      where: { postId, isDeleted: false },
    });
    if (!findPost) {
      throw new HttpException('文章不存在', HttpStatus.BAD_REQUEST);
    }

    return await this.postRepository.update(postId, data);
  }

  async fakeRemove(postId: number) {
    const findPost = await this.postRepository.findOne({
      where: { postId, isDeleted: false },
    });
    if (!findPost) {
      throw new HttpException('文章不存在', HttpStatus.BAD_REQUEST);
    }

    findPost.isDeleted = true;
    return await this.postRepository.save(findPost);
  }
}
